package com.itouch.bracelet.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.gson.Gson;
import com.itouch.bracelet.R;
import com.itouch.bracelet.adapter.ImageAdapter;
import com.itouch.bracelet.bean.BaseResult;
import com.itouch.bracelet.bean.UploadResult;
import com.itouch.bracelet.cache.UserCache;
import com.itouch.bracelet.diseaseinfo.Constants;
import com.itouch.util.CommonMethodTools;
import com.itouch.util.JsonAndPhpUtil;
import com.itouch.util.LoadingDialog;
import com.itouch.widget.ActionSheet;
import com.itouch.widget.ActionSheet.ActionSheetListener;

/***
 * 

* @ClassName: FriendCircleAddActivity 

* @Description: TODO(发表朋友圈) 

* @author sunshineHu hucx@itouch.com.cn

* @date 2015年2月9日 上午10:13:04 

*
 */
public class FriendCircleAddActivity extends SherlockFragmentActivity implements OnItemClickListener,OnClickListener,ActionSheetListener{

	private File image;
	
	private List<UploadResult> lists;
	private ImageAdapter adapter;
	
	private LoadingDialog loadingDialog;

	private EditText content;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friend_circle_add_layout);
		
		if(getSupportActionBar()!=null){
			getSupportActionBar().hide();
		}
		
		loadView();
	}

	private void loadView(){
		
		lists=new ArrayList<UploadResult>();
		
		GridView gridview=(GridView) findViewById(R.id.gridview);
		adapter=new ImageAdapter(this,lists);
		gridview.setAdapter(adapter);
		gridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
		gridview.setOnItemClickListener(this);
		
		content=(EditText) findViewById(R.id.content);
		
		TextView right=(TextView) findViewById(R.id.right);
		right.setOnClickListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		if(position==lists.size()){
			setTheme(R.style.ActionSheetStyleIOS7);
			ActionSheet.createBuilder(this, getSupportFragmentManager())
			.setCancelButtonTitle("取消")
			.setOtherButtonTitles("拍照", "从相册选择")
			.setCancelableOnTouchOutside(true).setListener(this).show();
		}
	}

	@Override
	public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onOtherButtonClick(ActionSheet actionSheet, int index) {
		// TODO Auto-generated method stub
		if(index==0){
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			image=new File(Environment.getExternalStorageDirectory(),"temp.jpg");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image));
            startActivityForResult(intent, 2);
		}else if(index==1){
			Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.addCategory(Intent.CATEGORY_OPENABLE);
			intent.setType("image/*");
			startActivityForResult(intent, 3);
		}
	}
	
	

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, data);
		if(arg1==RESULT_OK){
			if(arg0==3){

				Uri uri = data.getData();   
		        String [] proj={MediaStore.Images.Media.DATA};  
		        Cursor cursor = managedQuery( uri,  
		                proj,                 // Which columns to return  
		                null,       // WHERE clause; which rows to return (all rows)  
		                null,       // WHERE clause selection arguments (none)  
		                null);                 // Order-by clause (ascending by name)  
		          
		        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);  
		        cursor.moveToFirst();  
		          
		        String path = cursor.getString(column_index);  
				
		        image=new File(path);
		        
			}
			
/*			try {
				show();
				RequestParams params=new RequestParams();
				params.add("shopId", ApplicationCache.INSTANCE.getUserInfo().getShop().getId());
				params.put("Image", image);
				HttpTool.HttpPost(2, mContext, ApplicationConstants.SERVER_URL+"/mobi/ser/saveShopImage", params, this, new TypeToken<BaseResult<ShopImage>>() {
				}.getType());
				
				
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				disMiss();
			}*/
			new uploadImage().execute(image);
		}
	}
	
	

	/**
	 * 显示进度加载
	 */
	public void show() {
		if (loadingDialog == null) {
			loadingDialog = LoadingDialog.createDialog(this);
			// 点击外部区域，是否消失loadingDialog
			loadingDialog.setCanceledOnTouchOutside(false);
		}
		loadingDialog.setMessage("正在加载");
		loadingDialog.show();
	}

	/**
	 * 关闭进度加载
	 */
	public void disMiss() {
		if (loadingDialog != null) {
			loadingDialog.dismiss();
			loadingDialog = null;
		}
	}

	
	class uploadImage extends AsyncTask<File, Object, UploadResult>{

		@Override
		protected UploadResult doInBackground(File... params) {
			// TODO Auto-generated method stub
			String ss=CommonMethodTools.uploadFile(image, Constants.URL+"/mobi/friendCircle/singleUploadAttachment");
			UploadResult result=new Gson().fromJson(ss, UploadResult.class);
			return result;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			show();
		}

		@Override
		protected void onPostExecute(UploadResult result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			disMiss();
			if(result!=null){
				lists.add(result);
				adapter.notifyDataSetChanged();
			}
		}
		
	}

	
	class newInfo extends AsyncTask<String, Object, BaseResult>{


		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			show();
		}

		@Override
		protected void onPostExecute(BaseResult result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			disMiss();
			if(result!=null&&result.isFlag()){
				Toast.makeText(FriendCircleAddActivity.this, "保存成功！", Toast.LENGTH_SHORT).show();
				setResult(RESULT_OK);
				finish();
			}
		}

		@Override
		protected BaseResult doInBackground(String... params) {
			// TODO Auto-generated method stub
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			
			String pictures="";
			for(int i=0;i<lists.size();i++){
				if(i==0){
					pictures=lists.get(i).getPath();
				}else{
					pictures=pictures+","+lists.get(i).getPath();
				}
			}
			
			list.add(new BasicNameValuePair("content", content.getText().toString()));
			list.add(new BasicNameValuePair("creator", UserCache.getOauth(FriendCircleAddActivity.this).getUserId()));
			list.add(new BasicNameValuePair("pic", pictures));
			list.add(new BasicNameValuePair("title", ""));
			String ss = JsonAndPhpUtil.postHttpData(Constants.URL+"/mobi/friendCircle/insertFriend",list, FriendCircleAddActivity.this);	
			BaseResult re=new Gson().fromJson(ss, BaseResult.class);
			return re;
		}
		
	}

	

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		new newInfo().execute("");
	}
	

	
	public void back(View v){
		finish();
	}
	
}
